package com.jeesite.modules.isys.common.aop.check;

import com.jeesite.modules.isys.common.aop.dict.DictUtils;
import com.jeesite.modules.isys.common.aop.query.NullExec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.GenericTypeResolver;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class CheckObject {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private DictUtils dictUtils;


    @Autowired
    private NullExec nullExec;

    Map<Class,CheckEntity> checks = new HashMap<>();

    public Object check(Object object) throws Exception {
        if (object == null){
            return object;
        }

        //对参数进行字典处理
        dictUtils.parseObj(object, PARSE.RES);
        //处理其他操作
        CheckEntity check = getBean(object);
        if (check!=null){
            object =    check.check(object);
        }
        return object;
    }


    public Object checkArg(Object object) throws Exception {

        if (object == null){
            return object;
        }

//空处理
        object =  nullExec.execObjNull(object);
        //对参数进行字典处理
        dictUtils.parseObj(object, PARSE.ARGS);
        //处理其他操作
        CheckEntity check = getBean(object);
        if (check!=null){
         object =    check.checkArg(object);
        }

        return object;
    }


    //负责维护一个bean列表
    public CheckEntity  getBean(Object object){
        if (checks==null||checks.isEmpty()){
            Map<String, CheckEntity> beansOfType = applicationContext.getBeansOfType(CheckEntity.class);

            //构建相关map
            if (!beansOfType.isEmpty()){
                for (CheckEntity checkEntity : beansOfType.values()){
                    if (checkEntity.getClass() == CheckEntity.class){
                        continue;
                    }
                    if (checkEntity != null){
                        Class<?> aClass = GenericTypeResolver.resolveTypeArgument(checkEntity.getClass(), CheckEntity.class);

                        //添加扫描到的bean
                        checks.put(aClass,checkEntity);
                    }

                }
            }
        }
        //如果仍然为空，不执行操作
        if (!checks.isEmpty()){
            return checks.get(object.getClass());
        }


        return  null;
    }


}
